import React, { useState, useRef } from'react';
import { Layout, Menu, Input, Button, Upload, message, Progress, Select, Spin } from 'antd';
import { UploadOutlined, FolderOpenOutlined, PictureOutlined } from '@ant-design/icons';
import styles from './file.module.css';
import Fuse from 'fuse.js';

const FileItem = ({ name, size, type, date }) => (
  <div className={styles.fileItemGrid}>
    <div className={styles.fileIcon}>
      {type === '图片'? (
        <PictureOutlined style={{ fontSize: 32 }} />
      ) : (
        <FolderOpenOutlined style={{ fontSize: 32 }} />
      )}
    </div>
    <div className={styles.fileDetails}>
      <p className={styles.filename}>{name}</p>
      <p className={styles.filemeta}>{size} · {type}</p>
      <p className={styles.filedate}>{date}</p>
    </div>
  </div>
);

const App = () => {
  const [selectedCategory, setSelectedCategory] = useState('文件');
  const [uploadingFiles, setUploadingFiles] = useState([]);
  const [viewMode, setViewMode] = useState('list');
  const [files, setFiles] = useState(() => {
    const storedFiles = JSON.parse(localStorage.getItem('uploadedFiles')) || [
      { name: '示例图片.jpg', size: '0.20MB', type: '图片', date: '2024/3/16' },
      { name: '演示文档.pdf', size: '0.15MB', type: '文件', date: '2024/3/16' },
    ];
    return storedFiles;
  });
  const uploadTimers = useRef({});
  const [searchKeyword, setSearchKeyword] = useState('');

  const handleUpload = ({ file, onSuccess }) => {
    const ext = file.name.split('.').pop().toLowerCase();
    const isImage = ['jpg', 'jpeg', 'png', 'gif'].includes(ext);

    const newFile = {
      name: file.name,
      size: `${(file.size / 1024 / 1024).toFixed(2)}MB`,
      type: isImage? '图片' : '文件',
      date: new Date().toLocaleDateString(),
      progress: 0,
      uploading: true
    };

    if (files.some(f => f.name === newFile.name) ||
      uploadingFiles.some(f => f.name === newFile.name)) {
      message.warning('文件已存在');
      return;
    }

    setUploadingFiles(prev => [...prev, newFile]);

    const timerId = Symbol();
    const timer = setInterval(() => {
      setUploadingFiles(prev => prev.map(f => {
        if (f.name === newFile.name) {
          const progress = Math.min(f.progress + Math.random() * 10, 100);
          if (progress >= 100) {
            clearInterval(timer);
            setTimeout(() => {
              onSuccess();

              const fileToSave = {...f, progress: 100, uploading: undefined };

              const storedFiles = JSON.parse(localStorage.getItem('uploadedFiles')) || [];
              const updatedFiles = [
               ...storedFiles.filter(item => item.name!== fileToSave.name),
                fileToSave
              ];
              localStorage.setItem('uploadedFiles', JSON.stringify(updatedFiles));

              setUploadingFiles(prev => prev.filter(item => item.name!== f.name));
              setFiles(prev => [
               ...prev.filter(item => item.name!== f.name),
                fileToSave
              ]);
            }, 300);
          }
          return {...f, progress };
        }
        return f;
      }));
    }, 200);

    uploadTimers.current[newFile.name] = timer;
  };

  const handleCancelUpload = (fileName) => {
    clearInterval(uploadTimers.current[fileName]);
    delete uploadTimers.current[fileName];
    setUploadingFiles(prev => prev.filter(f => f.name!== fileName));
  };

  const fuzzyMatch = (text, keyword) => {
    if (!keyword) return true;
    const lowerText = text.toLowerCase();
    const lowerKeyword = keyword.toLowerCase();
    return lowerText.includes(lowerKeyword);
  };

  const filteredFiles = files
   .filter(file =>
      selectedCategory === '全部'? true : file.type === selectedCategory
    )
   .filter(file => fuzzyMatch(file.name, searchKeyword));

  const fuse = new Fuse(filteredFiles, { keys: ['name'] });
  const results = searchKeyword? fuse.search(searchKeyword).map(result => result.item) : filteredFiles;

  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 2;

  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentItems = filteredFiles.slice(indexOfFirstItem, indexOfLastItem);

  const totalPages = Math.ceil(filteredFiles.length / itemsPerPage);

  const handlePageChange = (pageNumber) => {
    setCurrentPage(pageNumber);
  };

  const deleteFile = (fileName) => {
    if (window.confirm('确定要删除这个文件吗？')) {
      setFiles(prev => prev.filter(file => file.name!== fileName));

      const storedFiles = JSON.parse(localStorage.getItem('uploadedFiles')) || [];
      const updatedFiles = storedFiles.filter(file => file.name!== fileName);
      localStorage.setItem('uploadedFiles', JSON.stringify(updatedFiles));
    }
  };

  return (
    <Layout style={{ height: '100vh' }}>
      {/* 侧边栏 */}
      <Layout.Sider width={200} style={{ background: '#fff', paddingTop: 20 }}>
        <Menu
          mode="inline"
          selectedKeys={[selectedCategory]}
          onSelect={({ key }) => setSelectedCategory(key)}
          items={[
            {
              key: '文件',
              icon: <FolderOpenOutlined />,
              label: '文件',
            },
            {
              key: '图片',
              icon: <PictureOutlined />,
              label: '图片',
            }
          ]}
        />
      </Layout.Sider>

      {/* 主要内容 */}
      <Layout>
        <Layout.Header style={{
          padding: '0 20px',
          background: '#fff',
          display: 'flex',
          alignItems: 'center',
          gap: 20,
          boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
          zIndex: 1
        }}>
          <Upload customRequest={handleUpload} showUploadList={false}>
            <Button type="primary" icon={<UploadOutlined />} className={styles.uploadButton}>
              上传文件
            </Button>
          </Upload>

          <Spin
            spinning={uploadingFiles.length > 0}
            indicator={<Progress type="circle" percent={100} />}
          >
            <span style={{ marginLeft: 8 }}>
              {uploadingFiles.length}个文件上传中...
            </span>
          </Spin>
        </Layout.Header>

        <Layout.Content style={{ margin: '20px', background: '#fff', padding: '20px' }}>
          {/* 文件管理头部 */}
          <div className={styles.AppHeader}>
            <h2>{selectedCategory}管理</h2>
            <div className={styles.controls}>
              <Input.Search
                placeholder="搜索文件"
                allowClear
                enterButton
                style={{ width: 300 }}
                value={searchKeyword}
                onChange={(e) => setSearchKeyword(e.target.value)}
                className={styles.searchButton}
              />
              <div className={styles.viewButtons}>
                <Button
                  onClick={() => setViewMode('list')}
                  type={viewMode === 'list'? 'primary' : 'default'}
                  className={`${styles.viewModeButton} ${viewMode === 'list'? styles.viewModeButtonActive : ''}`}
                >
                  列表视图
                </Button>
                <Button
                  onClick={() => setViewMode('grid')}
                  type={viewMode === 'grid'? 'primary' : 'default'}
                  className={`${styles.viewModeButton} ${viewMode === 'grid'? styles.viewModeButtonActive : ''}`}
                >
                  网格视图
                </Button>
              </div>
            </div>
          </div>

          {/* 文件列表 */}
          <div className={`${styles.fileContainer} ${viewMode === 'list'? styles.fileContainerList : styles.fileContainerGrid}`}>
            {currentItems.map(file => (
              viewMode === 'list'? (
                <div className={styles.fileItemList} key={file.name}>
                  <FileItem {...file} />
                  <Button
                    type="link"
                    danger
                    onClick={() => deleteFile(file.name)}
                    style={{ marginTop: 8 }}
                    className={styles.deleteButton}
                  >
                    删除
                  </Button>
                </div>
              ) : (
                <FileItem key={file.name} {...file} />
              )
            ))}

            {/* 上传中的文件 */}
            {uploadingFiles.map(file => (
              <div key={file.name} className={styles.uploadingFile}>
                <FileItem {...file} />

                <Progress
                  type={viewMode === 'list'? 'line' : 'circle'}
                  percent={Math.round(file.progress)}
                  status="active"
                  strokeColor={{
                    '0%': '#1890ff',
                    '100%': '#52c41a',
                  }}
                />
                <Button
                  type="link"
                  danger
                  onClick={() => handleCancelUpload(file.name)}
                  className={styles.deleteButton}
                >
                  取消
                </Button>
              </div>
            ))}

          </div>
          <div style={{ marginTop: '20px', textAlign: 'center' }}>
            <span>第 {currentPage} 页 / 共 {totalPages} 页</span>
            <div style={{ display: 'flex', justifyContent: 'center', gap: '10px', marginTop: '10px' }}>
              {Array.from({ length: totalPages }, (_, index) => (
                <Button
                  key={index + 1}
                  type={currentPage === index + 1? 'primary' : 'default'}
                  onClick={() => handlePageChange(index + 1)}
                  className={`${styles.paginationButton} ${currentPage === index + 1? styles.paginationButtonActive : ''}`}
                >
                  {index + 1}
                </Button>
              ))}
            </div>
          </div>
        </Layout.Content>
      </Layout>
    </Layout>
  );
};

export default App;